package com.googlecode.mailnet.netmodel;

import java.io.Serializable;

/**
 * Route description for a {@link MessageFlow}.
 *
 * @author Iskander Akishev
 */
public class Route implements Serializable {

	public Node getSource() {
		return source;
	}

	public int getLinksCount() {
		return links.length;
	}

	public Link getLink(int index) {
		return links[index];
	}

	public Node getDestination() {
		return links[links.length - 1].getDestination();
	}

	// ==================== Implementation ====================
	
	private final MessageFlow flow;
	private final Node source;
	private final Link[] links;

	Route(MessageFlow flow, Link[] links) {
		assert (!flow.isRemoved());
		flow.clearRoute();
		flow.route = this;
		this.flow = flow;

		if (links.length < 1) {
			throw new IllegalArgumentException("There must be at least one link in the route");
		}
		source = links[0].getSource();
		Node current = source;
		for (Link link : links) {
			if (link.networkConfiguration != flow.networkConfiguration) {
				throw new IllegalArgumentException("Network mismatch");
			}
			if (link.isRemoved()) {
				throw new IllegalArgumentException("Link is removed");
			}
			if (link.getSource() != current) {
				throw new IllegalArgumentException("Discontinuous route");
			}
			boolean result = link.usingRoutes.add(this);
			assert result;
			current = link.getDestination();
		}
		this.links = links.clone();
	}

	void remove() {
		assert flow.route == this;
		flow.route = null;

		for (Link link : links) {
			boolean result = link.usingRoutes.remove(this);
			assert result;
		}
	}

}
